package juc.collection;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
/*
UUID
 */

public class ListDemo {
    public static void main(String[] args) {
        //java.util.ConcurrentModificationException
        //Map<String,String> map = new HashMap<>();
        //1、使用ConcurrentHashMap<>()保证线程安全
        //Map<String,String> map = new ConcurrentHashMap<>();
        //使用Collections.synchronizedMap(new HashMap<>())保证线程安全
        Map<String,String> map = Collections.synchronizedMap(new HashMap<>());

        for(int i = 1;i<=30;i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }

    public static void setNotSafe() {
        //多线程环境下会出现java.util.ConcurrentModificationException
        //Set<String> set = new HashSet<>();
        //解决1、使用Collections.SynchronizedSet(set<T>());
        //Set<String> set = Collections.synchronizedSet(new HashSet<>());
        //方式2 使用CurrentHashSet<>();
        Set<String> set = new CopyOnWriteArraySet<>();

        for(int i = 1;i<=10;i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }

    private static void listNoSafe() {
        //ArrayList线程不安全验证
        //List<String> list = new ArrayList<>();
        //List<String> list = new Vector<>();
        //如何将一个线程不安全的集合类转为线程安全
        //List<String> list = Collections.synchronizedList(new ArrayList<>());
        //写实复制
        /*
        public class CopyOnWriteArrayList<E>
            implements List<E>, RandomAccess, Cloneable, java.io.Serializable
         */
        List<String> list = new CopyOnWriteArrayList<>();
        for(int i=1;i <=3;i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}
